#include "World.h"
#include "Tile.h"
#include "Item.h"
#include "Position.h"
#include "Creature.h"

World::World()
{
	bool first = true;
	for(int x = 0; x < 20; ++x)
	{
		for(int y = 0; y < 20; ++y)
		{
			if(first)
			{	
			first = false;
			continue;
			}
			
			Tile* tile = getTile(x, y, 0);
			
			Item* item = new Item();
			item->setId(102);
			tile->addThing(item);
			
			Item* item2 = new Item();
			item2->setId(rand() % 1000 + 1000);
			tile->addThing(item2);
		}
	}
	
	Creature* creature = new Creature();
	Tile* tile = getTile(5, 3, 0);
	
	if(tile)
		tile->addThing(creature);
}

World::~World()
{
	//
}

Tile* World::getTile(const Position& pos)
{
	return getTile(pos.x, pos.y, pos.z);
}

Tile* World::getTile(uint16_t x, uint16_t y, uint8_t z)
{
	Tile* tile = 0;
	
	if(m_tiles[x][y])
	{
		return m_tiles[x][y];
	}
	
	tile = new Tile();
	tile->setPosition(x, y, z);
	
	return setTile(x, y, z, tile);
}

Tile* World::setTile(const Position& pos, Tile* tile)
{
	return setTile(pos.x, pos.y, pos.z, tile);
}

Tile* World::setTile(uint16_t x, uint16_t y, uint8_t z, Tile* tile)
{
	if(m_tiles[x][y])
	{
		delete m_tiles[x][y];
		m_tiles[x][y] = 0;
	}
	
	m_tiles[x][y] = tile;
	return tile;
}
